<template>
    <div class="score">
        <br />
        <div class="total">
            <div class="look">
                <i class="el-icon-a-061" style="font-size: 32px;">
                    {{ institute }}{{ studentName }}，你的本次考试成绩为
                </i>
            </div>

            <!-- 分数展示 -->
            <div class="show">
                <div class="number" :class="{ border: isTransition }">
                    <span>{{ score }}</span>
                    <span>分</span>
                </div>
            </div>

            <!-- 考试时间信息 -->
            <ul class="time">
                <li class="start">
                    <span>开始时间</span>
                    <span>{{ startTime }}</span>
                </li>
                <li class="end">
                    <span>结束时间</span>
                    <span>{{ endTime }}</span>
                </li>
                <!-- 新增：考试时长（精确到秒） -->
                <li class="duration">
                    <span>考试时长</span>
                    <span>{{ duration }}</span>
                </li>
            </ul>

            <!-- 查看错题按钮 -->
            <button
            class="toggle-btn"
            @click="toggleMistakes"
            aria-expanded="false"
            >
            {{ showMistakes ? '收起错题解析' : '查看错题解析' }}
            </button>

            <div
            v-if="showMistakes"
            class="mistake-overlay"
            @click="showMistakes = false"
            ></div>
        </div>



        <!-- 查看错题部分 -->
        <div v-if="showMistakes" class="mistake-container">
            <div v-if="this.wrongQuestions.length === 0" class="no-mistakes">
                <p>🎉 恭喜！全部答对，没有错题！</p>
            </div>


            <div
                v-for="(item, index) in wrongQuestions"
                :key="item.questionId"
                class="mistake-item"
            >
                <!-- 题号 -->
                <div class="question-header">
                    第 {{ index + 1 }} 题
                    <span class="type-tag">
                        ({{ {1: '单选', 2: '多选', 3: '判断'}[item.questionType] || '未知' }})
                    </span>
                </div>

                <!-- 题干 -->
                <div class="question-text">
                    {{ item.question }}
                </div>

                <!-- 根据题型渲染不同结构 -->
                <template v-if="item.questionType === 1 || item.questionType === 2">
                <!-- 显示我的答案 -->
                <div class="your-answer-label" v-if="item.yourAnswer && item.yourAnswer.length">
                    我的答案：<span class="answer-chips">{{ item.yourAnswer.split('').join('、') }}</span>
                </div>
                <div class="options-list" v-if="item.options">
                    <!-- 选项循环 -->
                    <div
                    v-for="(opt, key) in item.options"
                    :key="key"
                    class="option-item"
                    :class="{
                        'your-answer': item.yourAnswer.includes(key),
                        'correct-answer': item.correctAnswer.includes(key),
                        'wrong-answer': item.yourAnswer.includes(key) && !item.correctAnswer.includes(key),
                        'missed-correct': !item.yourAnswer.includes(key) && item.correctAnswer.includes(key)
                    }"
                    >
                    <div class="option-text">
                        <strong>{{ key }}.</strong>
                        <span>{{ opt }}</span>
                    </div>
                    <div class="option-icon">
                        <!-- 用户选择了 -->
                        <span v-if="item.yourAnswer.includes(key)">
                        {{ item.correctAnswer.includes(key) ? '✅' : '❌' }}
                        </span>
                        <!-- 用户没选但这是正确答案 -->
                        <span v-else-if="item.correctAnswer.includes(key)" class="wrong-icon">❌</span>
                    </div>
                    </div>
                </div>
                </template>

                <!-- 判断题 -->
                <template v-else-if="item.questionType === 3">
                <!-- 显示我的答案 -->
                <div class="your-answer-label">
                    我的答案：
                    <span class="answer-chips">{{ item.yourAnswer }}</span>
                </div>

                <div class="options-list">
                    <div
                        v-for="(text, key) in { A: '正确', B: '错误' }"
                        :key="key"
                        class="option-item"
                        :class="{
                            'your-answer': item.yourAnswer === text,
                            'correct-answer': item.correctAnswer === text,
                            'wrong-answer': item.yourAnswer === text && item.yourAnswer !== item.correctAnswer
                        }"
                    >
                    <div class="option-text">
                        <strong>{{ text }}</strong>
                    </div>
                    <div class="option-icon">
                        <!-- 只有用户选择了这个选项，才显示对错图标 -->
                        <span v-if="item.yourAnswer === text">
                        {{ item.correctAnswer === text ? '✅' : '❌' }}
                        </span>
                    </div>
                    </div>
                </div>
                </template>

                <!-- 正确答案 -->
                <div class="correct-answer-line">
                    正确答案：
                    <span class="badge correct">
                        {{ formatAnswerDisplay(item.correctAnswer, item.questionType) }}
                    </span>
                    
                </div>
                
                <!-- 解析 -->
                <div v-if="item.analysis" class="analysis-box">
                    <strong>📘 解析：</strong>
                    <p>{{ item.analysis }}</p>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
export default {
    data() {
        return {
            isTransition: false, // 是否渲染完成
            score: 0, // 总分
            startTime: null, // 考试开始时间
            endTime: null, // 考试结束时间
            studentName: "考生", // 学生姓名（默认值）
            institute: '', // 学院
            duration: "" ,// 考试时长（精确到秒）
            wrongQuestions:[], //错题

            showMistakes: false
        };
    },
    created() {
        this.transiton();
        this.getScore();
        this.getInstitute(); // 获取学生信息（含学院）
        
        this.getMistakesFromStorage();
    },
    methods: {
        transiton() {
            // 一秒后过渡
            setTimeout(() => {
                this.isTransition = true;
            }, 1000);
        },

        toggleMistakes() {
            this.showMistakes = !this.showMistakes;
        },

        // 获取成绩和时间等信息
        getScore() {

            // console.log('this.$route.query :>> ', this.$route.query);

            let score = this.$route.query.score;
            let startTime = this.$route.query.startTime;
            let endTime = this.$route.query.endTime;
            let studentNameFromQuery = this.$route.query.studentName;

            this.score = score || 0;
            this.startTime = startTime || null;
            this.endTime = endTime || null;

            // 如果 query 中有名字，优先使用；否则留空，等待接口返回
            if (studentNameFromQuery) {
                this.studentName = studentNameFromQuery;
            }
            // 否则由 getInstitute 接口填充

            // 计算考试时长
            if (startTime && endTime) {
                const start = new Date(startTime);
                const end = new Date(endTime);
                const diffMs = end - start;

                if (isNaN(diffMs)) {
                    this.duration = "时间格式无效";
                    return;
                }

                const totalSeconds = Math.floor(diffMs / 1000);
                const hours = Math.floor(totalSeconds / 3600);
                const minutes = Math.floor((totalSeconds % 3600) / 60);
                const seconds = totalSeconds % 60;

                let timeParts = [];
                if (hours > 0) timeParts.push(`${hours}小时`);
                if (minutes > 0) timeParts.push(`${minutes}分钟`);
                timeParts.push(`${seconds}秒`);

                this.duration = timeParts.join('');
            } else {
                this.duration = "未知";
            }
        },

        // ✅ 异步获取学生信息（包括学院）
        async getInstitute() {
            const id = this.$route.query.studentId;
            // console.log('studentId :>> ', id);

            if (!id || isNaN(id)) {
                // console.error('无效的 studentId:', id);
                this.institute = '';
                return;
            }

            try {
                const response = await this.$axios.get(`/api/student/${id}`);
                // console.log('API 响应 :>> ', response.data);

                if (response.data.code === 200 && response.data.data) {
                    const student = response.data.data;
                    // 只有当 query 没传 name 时才用接口的
                    if (!this.$route.query.studentName) {
                        this.studentName = student.studentName || '考生';
                    }
                    this.institute = student.institute ? student.institute + ' ' : '';
                } else {
                    // console.warn('查询失败:', response.data.message);
                    this.institute = '';
                }
            } catch (error) {
                // console.error('请求学生信息失败:', error);
                this.institute = '';
            }
        },

        getMistakesFromStorage() {
            try {
                this.wrongQuestions = this.$route.query.wrongQuestions;
                // console.table(this.wrongQuestions)
            } catch (error) {
                // console.error('解析错题失败:', error);
                this.wrongQuestions = [];
            }
        },

        // 格式化答案显示（用于正确答案展示）
        formatAnswerDisplay(answer, type) {
            if (type === 3) {
                // 判断题：correctAnswer 已经是 "正确"/"错误"，直接返回
                return answer; // ✅ 直接返回即可
            }
            // 单选/多选：原样返回（如 A、AB、ACD）
            return answer;
        }
    }
};
</script>

<style lang="less" scoped>
/* 样式部分保持不变 */
.show {
    display: flex;
    justify-content: center;
    align-items: center;
    img {
        width: 160px;
        height: 160px;
    }
    .img1Transform {
        opacity: 1 !important;
        transform: translateX(30px) !important;
        transition: all 0.6s ease !important;
    }
    .img2Transform {
        opacity: 1 !important;
        transform: translateX(-30px) !important;
        transition: all 0.6s ease !important;
    }
    .img1 {
        margin-top: 70px;
        opacity: 0;
        transform: translateX(0px);
        transition: all 0.6s ease;
    }
    .img2 {
        margin-top: 30px;
        opacity: 0;
        transform: translateX(0px);
        transition: all 0.6s ease;
    }
}

.time {
    padding: 0px 70px;
    li {
        display: flex;
        justify-content: space-around;
        padding: 10px;
        margin: 20px 0px;
    }
    li:nth-child(1) {
        background-color: #fcf8e3;
    }
    li:nth-child(2) {
        background-color: #e9f5e9;
    }
    li.duration {
        background-color: #e3f2fd;
    }
}

.border {
    border: 6px solid #36aafd !important;
    transition: all 2s ease;
    width: 160px !important;
    height: 160px !important;
    transform: rotate(360deg) !important;
    opacity: 1 !important;
}

.score {
    max-width: 800px;
    margin: 0 auto;
    .title {
        margin: 60px 0px 30px 0px;
        display: flex;
        justify-content: center;
        align-items: center;
        flex-direction: column;
        .name {
            font-size: 26px;
            color: inherit;
            font-weight: 500;
        }
        .description {
            font-size: 14px;
            color: #888;
        }
    }
    .total {
        border: 1px solid #dbdbdb;
        background-color: #fff;
        padding: 40px;
        .look {
            border-bottom: 1px solid #dbdbdb;
            padding: 0px 0px 14px 14px;
            color: #36aafd;
        }
        .number {
            opacity: 0;
            border: 6px solid #fff;
            transform: rotate(0deg);
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            margin: 0 auto;
            width: 160px;
            height: 160px;
            border-radius: 50%;
            margin-top: 80px;
            margin-bottom: 20px;
            transition: all 1s ease;
            span:nth-child(1) {
                font-size: 36px;
                font-weight: 600;
            }
            span:nth-child(2) {
                font-size: 14px;
            }
        }
    }

    /* 错题容器 */
    .mistake-container {
    margin-top: 30px;
    font-family: "Microsoft YaHei", "Segoe UI", sans-serif;
    }

    /* 每道题的外层容器 */
    .mistake-item {
    padding: 20px;
    margin-bottom: 24px;
    background: #ffffff;
    border: 1px solid #eaeaea;
    border-radius: 12px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
    transition: box-shadow 0.3s ease;
    }

    .mistake-item:hover {
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
    }

    /* 题号 */
    .question-header {
    font-size: 16px;
    font-weight: bold;
    color: #1f2d3d;
    margin-bottom: 12px;
    padding-bottom: 8px;
    border-bottom: 2px solid #f0f0f0;
    }

    /* 题干 */
    .question-text {
    font-size: 17px;
    font-weight: 500;
    color: #333;
    margin-bottom: 16px;
    line-height: 1.6;
    padding: 10px 0;
    }

    /* 选项列表 */
    .options-list {
    margin: 16px 0;
    display: flex;
    flex-direction: column;
    gap: 10px;
    }

    /* 每个选项 */
    .option-item {
    font-size: 15px;
    padding: 12px 16px;
    border: 1px solid #e8e8e8;
    border-radius: 8px;
    background-color: #fbfbfb;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;           /* 垂直居中 */
    justify-content: space-between; /* 内容两端分布 */
    color: #555;
    min-height: 44px;               /* 保持行高一致 */
    }

    /* 选项文字部分（A. 内容） */
    .option-item .option-text {
    display: flex;
    align-items: center;
    flex: 1;                       /* 占据剩余空间 */
    gap: 8px;                      /* 图标与文字间距 */
    }

    .option-item .option-text strong {
    flex-shrink: 0;                /* 防止 A. 被压缩 */
    width: 20px;                   /* 固定宽度，对齐 */
    text-align: center;
    }

    /* 图标部分 */
    .option-item .option-icon {
    flex-shrink: 0;
    margin-left: 12px;
    font-weight: bold;
    }

    /* 正确/错误图标颜色 */
    .correct-icon {
    color: #67c23a;
    font-size: 18px;
    }

    .wrong-icon {
    color: #f56c6c;
    font-size: 18px;
    }

    /* 你的答案 */
    .option-item.your-answer {
    border-color: #409eff;
    background-color: #f0f7ff;
    color: #409eff;
    font-weight: bold;
    }

    /* 正确答案高亮 */
    .option-item.correct-answer {
    border-color: #67c23a;
    background-color: #f0fff0;
    color: #67c23a;
    }

    /* 错误答案标记 */
    .option-item.wrong-answer {
    border-color: #f56c6c;
    background-color: #fff0f0;
    color: #f56c6c;
    }

    /* 正确答案行 */
    .correct-answer-line {
    font-size: 15px;
    margin: 12px 0;
    color: #333;
    }

    .badge {
    padding: 4px 10px;
    border-radius: 6px;
    font-weight: bold;
    font-size: 14px;
    }

    .badge.correct {
    background-color: #67c23a;
    color: white;
    border: 1px solid #67c23a;
    }

    /* 解析区域 */
    .analysis-box {
    margin-top: 16px;
    padding: 14px;
    background-color: #e3f2fd;
    border-left: 4px solid #2196f3;
    border-radius: 6px;
    font-size: 14px;
    color: #1976d2;
    line-height: 1.5;
    }

    .analysis-box p {
        margin: 6px 0;
    }

    /* 无错题提示 */
    .no-mistakes {
        text-align: center;
        padding: 40px 20px;
        background-color: #f0fff0;
        border-radius: 12px;
        border: 1px dashed #67c23a;
        color: #67c23a;
        font-size: 18px;
        font-weight: bold;
    }

    /* 查看错题按钮 */
    .toggle-btn {
        display: block;
        margin: 30px auto;
        padding: 14px 32px;
        font-size: 16px;
        font-weight: 600;
        text-transform: uppercase;
        letter-spacing: 0.8px;
        color: #fff;
        background: linear-gradient(135deg, #409eff, #2d7eff);
        border: none;
        border-radius: 30px;
        cursor: pointer;
        transition: all 0.3s ease;
        box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
        outline: none;
        position: relative;
        overflow: hidden;
    }

    .toggle-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 16px rgba(64, 158, 255, 0.4);
        background: linear-gradient(135deg, #337ecc, #206ad0);
    }

    .toggle-btn:active {
        transform: translateY(0);
        box-shadow: 0 2px 8px rgba(64, 158, 255, 0.3);
    }

    /* 按钮点击波效果（可选） */
    .toggle-btn::after {
        content: '';
        position: absolute;
        top: 50%;
        left: 50%;
        width: 0;
        height: 0;
        background: rgba(255, 255, 255, 0.2);
        border-radius: 50%;
        transform: translate(-50%, -50%);
        transition: width 0.6s, height 0.6s;
        pointer-events: none;
    }

    .toggle-btn:active::after {
        width: 200px;
        height: 200px;
    }

    .type-tag {
        font-size: 12px;
        color: #999;
        margin-left: 8px;
        font-weight: normal;
    }

    /* 漏选的正确答案（红色边框 + 文字） */
    .option-item.missed-correct {
    border-color: #f56c6c;
    background-color: #fff0f0;
    color: #f56c6c;
    }

    /* 漏选项的图标位置 */
    .option-item.missed-correct .missed-icon {
    flex-shrink: 0;
    margin-left: 12px;
    font-weight: bold;
    }

    .partial-tip {
    font-size: 14px;
    color: #999;
    margin: 10px 0;
    text-align: center;
    }

    /* 你的答案 */
    .option-item.your-answer {
    border-color: #409eff;
    background-color: #f0f7ff;
    color: #409eff;
    font-weight: bold;
    }

    /* 正确答案高亮 */
    .option-item.correct-answer {
    border-color: #67c23a;
    background-color: #f0fff0;
    color: #67c23a;
    }

    /* 错误答案标记 */
    .option-item.wrong-answer {
    border-color: #f56c6c;
    background-color: #fff0f0;
    color: #f56c6c;
    }

    /* 我的答案标签 */
    .your-answer-label {
    font-size: 14px;
    color: #409eff;
    margin: 8px 0 4px;
    font-weight: bold;
    }

    .answer-chips {
    font-size: 15px;
    background-color: #e1f3ff;
    color: #409eff;
    padding: 2px 6px;
    border-radius: 4px;
    margin-left: 4px;
    font-weight: normal;
    }
}
</style>